package com.example.oj.Util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.oj.entity.User;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

import java.util.Date;


public class JWTUtil {
    private static final Logger log = LoggerFactory.getLogger(JWTUtil.class);
    private final static long EXPIRE_TIME = 2 * 3600 * 1000L;


    private final static String SECRET = "sdfksdakfsdkjafklajiejekjf";  // 密钥

    /**
     * 生成 token
     *
     * @param user
     * @return token
     */
    public static String JWT_Create(User user) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    .withClaim("id", user.getId())
                    .withClaim("role", user.getRole())
                    .withClaim("username", user.getUsername())
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 校验 token是否正确
     *
     * @param token token
     * @return
     */
    public static boolean JWT_Check(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 获取用户名
     *
     * @param token
     * @return
     */
    public static Integer JWT_getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asInt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String JWT_getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static Integer JWT_getRole(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("role").asInt(); // 数据类型别搞错了
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    public static void main(String[] args) {
//        String hello = JWT_Create(new User());
//        System.out.println(hello);
//        System.out.println(verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDU2MjQ4OTksInVzZXJuYW1lIjoiaGVsbG8ifQ.Yd6VkK3xyfU3It6brU9yyNU1WelbFX4HaAoqILDQbFw"));
//        System.out.println(getUsername(hello));
    }
}
